package org.example.service;

import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.example.model.DataSourceConfig;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @author by PengHongChao
 * @date 2025/7/7 10:20
 */
@Component
public class MySQLDataSourceProvider implements DataSourceProvider {
    private static final String TYPE = "mysql";

    @Override
    public DataSource createDataSource(DataSourceConfig config) {
        HikariConfig hikariConfig = new HikariConfig();
        hikariConfig.setJdbcUrl(config.getUrl());
        hikariConfig.setUsername(config.getUsername());
        hikariConfig.setPassword(config.getPassword());
        hikariConfig.setDriverClassName(config.getDriverClass());
        // 其他连接池配置
        hikariConfig.setMaximumPoolSize(10);
        hikariConfig.setMinimumIdle(2);
        return new HikariDataSource(hikariConfig);
    }

    @Override
    public boolean testConnection(DataSourceConfig config) {
        try (Connection conn = createDataSource(config).getConnection()) {
            // 3秒超时
            return conn.isValid(3);
        } catch (SQLException e) {
            return false;
        }
    }

    @Override
    public String getType() {
        return TYPE;
    }
}
